package com.example.coreshopapp.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.MainActivity;
import com.example.coreshopapp.R;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.DangbanReq;
import com.example.coreshopapp.bean.GoodsCategoryData;
import com.example.coreshopapp.bean.LoginData;
import com.example.coreshopapp.bean.LoginReq;
import com.example.coreshopapp.bean.SysuserData;
import com.example.coreshopapp.databinding.ActivityLoginBinding;
import com.example.coreshopapp.task.DangbanTask;
import com.example.coreshopapp.task.LoginTask;
import com.example.coreshopapp.utils.DeviceInfo;
import com.example.coreshopapp.utils.LoadingUtils;

public class LoginActivity extends BaseActivity {
    /**
     * 1.判断本地是或否有当班人
     * 2.有当班人：判断当前登录是否是当前当班人的登陆的账号，如果不是提示：当班人与当前登陆账号不一致，请重新登录
     */
    private ActivityLoginBinding binding;
    private boolean isPasswordVisible = false; // 状态标识
    private SharedPreferences userSP;
    private LoginData loginInfo;
    private LoginTask loginTask;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            //mSynDialog.dismiss();
            binding.btnLog.setEnabled(true); // 关闭按钮控制
            // 显示 loading icon（替换成你自己的 icon）
            binding.btnLog.setText("登录");
            switch (msg.what) {
                case 9900:
                    loginInfo = (LoginData) msg.obj;
                    loginTask.setUserHandler(userHandler);
                    loginTask.userExecute();
                    break;
                case 9901:
                    Toast.makeText(LoginActivity.this, "登录失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(LoginActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler userHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    // 拿到数据比对
                    Log.d("user ",msg.obj.toString());
                    successLogin(loginInfo);
                    break;
                case 9901:

                    break;
                case 9902:
                    Toast.makeText(LoginActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(LoginActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideTopBar();
        initView();
        getStorage();
        viewClick();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.AppConstVars.sysUser != null && Constants.AppConstVars.sysUser.getId() != 0) {
            gotoActivity(MainActivity.class);
            finish();
        }
    }


    private void getStorage() {
        userSP = getSharedPreferences("login", MODE_PRIVATE);
        String name = userSP.getString("name", "");
        String password = userSP.getString("password", "");
        if (!name.isEmpty() || !password.isEmpty()) {
            binding.nameLgEt.setText(name);
            binding.passwordLgEt.setText(password);
            binding.rememberPsd.setChecked(true);
        }

    }

    private void initView() {
        Constants.AppConstVars.Sn = DeviceInfo.getDeviceSerial(this).toString(); // 设备号
    }

    private void viewClick() {
        binding.showPassword.setOnClickListener(view -> {
            // 是否展示密码
            if (!isPasswordVisible) {
                // 转为输入
                binding.passwordLgEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                // 转为文本
                binding.passwordLgEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
            isPasswordVisible = !isPasswordVisible;
            // 重新设置光标位置
            binding.passwordLgEt.setSelection(binding.passwordLgEt.getText().length());
        });

    }

    public void onLogin(View view) {
        // 登陆
        String name = binding.nameLgEt.getText().toString().trim();
        String password = binding.passwordLgEt.getText().toString().trim();
        if (name.isEmpty() || password.isEmpty()) {
            showtoast(this, "请输入正确的值");
            return;
        }
        binding.btnLog.setEnabled(false);
        // 动态设置按钮icon
        SpannableString spannable = new SpannableString("登录  "); // 预留空间
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.loading_1);
        drawable.setBounds(0, 0, dpToPx(20), dpToPx(20));
        ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_CENTER);
        spannable.setSpan(imageSpan, spannable.length() - 1, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        binding.btnLog.setText(spannable);
        loginTask = new LoginTask(name, password);
        loginTask.setOutHandler(mHandler);
        loginTask.execute();
    }
    public int dpToPx( int dp) {
        float density = getActivity().getResources().getDisplayMetrics().density;
        return Math.round(dp * density); // 四舍五入
    }
    private void successLogin(LoginData obj) {
        // 登陆
        // 挡板信息由接口返回，不用进行判读
//        SharedPreferences dangbanInfo = getSharedPreferences("dangbanInfo", MODE_PRIVATE);
//        int sysuserId = dangbanInfo.getInt("sysuserId", 0);
        // 判断当前当班人信息是否与登录信息不符
//        if (dangbanInfo == null || sysuserId == 0 || sysuserId == Constants.AppConstVars.sysUser.getId()) {
            String name = binding.nameLgEt.getText().toString().trim();
            String password = binding.passwordLgEt.getText().toString().trim();
            SharedPreferences.Editor edit = getSharedPreferences("login", MODE_PRIVATE).edit();
            edit.putString("name", binding.rememberPsd.isChecked() ? name : "");
            edit.putString("password", binding.rememberPsd.isChecked() ? password : "");
            edit.apply();
            gotoActivity(MainActivity.class);
//        } else {
//            Constants.AppConstVars.token = "";
//            Constants.AppConstVars.sysUser = null;
//            showtoast(getActivity(), "当前当班人与登陆人不符");
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放绑定的引用，防止内存泄漏
        binding = null;
    }
}